package com.punch.order.asyn;

import com.punch.common.enums.order.OrderStatusEnum;
import com.punch.common.redis.utils.RedisUtil;
import com.punch.order.mapper.TimeTaskMapper;
import com.punch.order.model.TimeTask;
import com.punch.order.service.CommonOrderService;
import com.punch.order.service.TimeTaskService;
import com.punch.order.util.CronUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * OrderAsync-订单异步任务
 *
 * @author wujj
 * @version 1.0.0
 * @since 2020/8/11 18:42
 */
@Component
@Slf4j
@Async
public class OrderAsync {


    @Resource
    @Lazy
    private TimeTaskService timeTaskService;


    @Resource
    private TimeTaskMapper timeTaskMapper;

    @Resource
    private CommonOrderService commonOrderService;

    @Resource
    private RedisUtil redisUtil;


    /**
     * 添加动态定时任务
     *
     * @param orderId    订单id
     * @param createTime 创建时间
     */
    public void addUnPayTask(Long orderId, LocalDateTime createTime) {
        createTime.plusMinutes(30L);//未支付订单30分钟以后取消
        String timeCron = CronUtil.formatDateByPattern(createTime);
        TimeTask timeTask = new TimeTask();
        timeTask.setType(0);
        timeTask.setTimeCron(timeCron);
        timeTask.setAssociateId(orderId);
        timeTask.setAssociateType(0);//班级开始报名
        timeTaskMapper.insert(timeTask);
        timeTaskService.addCron(timeTask.getId(), 0, orderId, 0, timeCron);
        String key = "timeTask:" + orderId;
        Long value = timeTask.getId();
        redisUtil.setValue(key, value);
    }


    /**
     * 未支付订单取消
     *
     * @param timeTaskId  定时任务id
     * @param associateId 关联的订单id
     */
    @Transactional(rollbackFor = Exception.class)
    public void unPayCancel(Long timeTaskId, Long associateId) {
        timeTaskMapper.deleteById(timeTaskId);
        commonOrderService.updateOrderStatus(associateId, OrderStatusEnum.HAVE_CANCEL.getCode());
    }
}
